<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="supplier-list-container">
    <!-- 搜索和筛选区 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.supplierName"
            placeholder="请输入供应商名称"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="供应商状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择供应商状态"
            clearable
            style="width: 180px;"
          >
            <el-option label="正常合作" value="1" />
            <el-option label="合作终止" value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-button type="primary" @click="handleAdd">
          <i class="el-icon-plus"></i> 新增供应商
        </el-button>
      </el-form>
    </el-card>

    <!-- 供应商列表 -->
    <el-card class="list-card">
      <el-table
        :data="supplierList"
        border
        stripe
        v-loading="loading"
        element-loading-text="加载中..."
        style="width: 1300px;"
      >
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center"
        />

        <el-table-column
          prop="supplierName"
          label="供应商名称"
          min-width="130"
        />

        <el-table-column
          prop="phone"
          label="联系电话"
          min-width="120"
        />

        <el-table-column
          prop="address"
          label="地址"
          min-width="140"
        >
          <template #default="scope">
            <el-tooltip :content="scope.row.address || '无地址'">
              <div class="ellipsis">{{ scope.row.address || '无地址' }}</div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column
          prop="status"
          label="供应商状态"
          min-width="120"
        >
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常合作' : '合作终止' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="updateTime"
          label="最后更新时间"
          min-width="160"
        >
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          min-width="140"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
              style="color: #409EFF;"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row.id)"
              style="color: #F56C6C;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.pageNum"
          :page-sizes="[10,15, 20]"
          :page-size="pagination.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="!loading && total === 0">
        <el-empty description="暂无供应商数据">
          <el-button type="primary" @click="handleAdd">新增供应商</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 供应商表单弹窗 (新增/编辑) -->
    <SupplierForm
      v-model:visible="formVisible"
      :model-value="currentSupplier"
      @save="handleSave"
    />

    <!-- 供应商详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="供应商详情"
      :width="600"
      :close-on-click-modal="false"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="供应商名称">{{ currentSupplier.supplierName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentSupplier.phone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系地址">{{ currentSupplier.address || '-' }}</el-descriptions-item>
        <el-descriptions-item label="供应商状态">
          {{ currentSupplier.status === 1 ? '正常合作' : currentSupplier.status === 0 ? '合作终止' : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatTime(currentSupplier.createTime) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最后更新时间">{{ formatTime(currentSupplier.updateTime) || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus';
import { reactive, ref, onMounted } from 'vue';
import { getProviders, deleteProvider, updateProvider, createProvider, searchProvidersByName } from '@/api/provide';
import SupplierForm from './components/create.vue';

// 供应商列表数据
const supplierList = ref([]);
const loading = ref(false);
const total = ref(0);

// 搜索表单
const searchForm = reactive({
  supplierName: '',
  status: ''
});

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10
});

// 弹窗控制
const formVisible = ref(false);
const detailVisible = ref(false);
const currentSupplier = ref({});

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  try {
    const date = new Date(time);
    return date.toLocaleString();
  } catch (error) {
    console.error('时间格式化失败:', error);
    return time;
  }
};

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    loading.value = true;

    // 如果有供应商名称查询条件，使用按名称查询接口
    if (searchForm.supplierName && searchForm.supplierName.trim() !== '') {
      await searchSuppliersByName();
      return;
    }

    // 否则使用分页查询接口
    const params = {
      pageNo: Number(pagination.pageNum),
      pageSize: Number(pagination.pageSize)
    };

    // 处理状态筛选
    if (searchForm.status !== '' && searchForm.status !== undefined) {
      params.status = Number(searchForm.status);
    }

    const res = await getProviders(params);
    supplierList.value = res.data.records || [];
    total.value = res.data.total || 0;
  } catch (error) {
    ElMessage.error('获取供应商列表失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 按名称搜索供应商（更新实现）
const searchSuppliersByName = async () => {
  try {
    const params = {
      supplierName: searchForm.supplierName.trim(),
      pageNo: Number(pagination.pageNum),
      pageSize: Number(pagination.pageSize)
      // 注意：按名称查询接口不支持status参数，所以不传递该参数
    };

    const res = await searchProvidersByName(params);
    if (res.code === 0 || res.code === 200) {
      supplierList.value = res.data.records || [];
      total.value = res.data.total || 0;

      // 如果有状态筛选，在前端进行过滤
      if (searchForm.status !== '' && searchForm.status !== undefined) {
        const statusValue = Number(searchForm.status);
        supplierList.value = supplierList.value.filter(record => record.status === statusValue);
        // 注意：前端筛选会改变实际显示数量，但分页信息仍来自后端
      }
    } else {
      ElMessage.error('查询供应商失败: ' + (res.msg || '未知错误'));
      supplierList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error('查询供应商失败: ' + (error.message || '网络异常'));
    console.error(error);
    supplierList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 重置搜索（补充修复：确保重置后参数为空字符串而非undefined）
const resetSearch = () => {
  searchForm.supplierName = '';  // 明确设为空字符串
  searchForm.status = '';        // 明确设为空字符串
  pagination.pageNum = 1;
  fetchSupplierList();
};

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1;
  fetchSupplierList();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  fetchSupplierList();
};

// 当前页码变化
const handleCurrentChange = (page) => {
  pagination.pageNum = page;
  fetchSupplierList();
};

// 新增供应商
const handleAdd = () => {
  currentSupplier.value = {};
  formVisible.value = true;
};

// 编辑供应商
const handleEdit = (row) => {
  currentSupplier.value = JSON.parse(JSON.stringify(row));
  formVisible.value = true;
};

// 查看供应商详情
const handleView = (row) => {
  currentSupplier.value = { ...row };
  detailVisible.value = true;
};

// 删除供应商
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该供应商吗？', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await deleteProvider(id);
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('删除成功');
      fetchSupplierList();
    } else {
      ElMessage.error('删除失败: ' + (res.msg || '未知错误'));
    }
  } catch (error) {
    if (error === 'cancel') return;
    ElMessage.error('删除失败: ' + (error.message || '操作被中断'));
    console.error(error);
  }
};

// 保存供应商（新增或编辑）
const handleSave = async (formData) => {
  try {
    loading.value = true;

    let res;
    if (formData.id) {
      // 编辑操作 - 增加乐观锁或版本控制支持（如果后端需要）
      res = await updateProvider({
        ...formData,
        // 如果后端有版本字段，需要传递
        // version: currentSupplier.value.version
      });
    } else {
      // 新增操作
      res = await createProvider(formData);
    }

    // 更严格的响应判断
    if ([0, 200].includes(res.code)) {
      ElMessage.success(formData.id ? '编辑成功' : '新增成功');
      formVisible.value = false;
      fetchSupplierList(); // 重新加载列表
    } else {
      ElMessage.error(`操作失败: ${res.msg || '服务器返回异常'}`);
    }
  } catch (error) {
    const action = formData.id ? '编辑' : '新增';
    if (error.response) {
      // 处理HTTP错误响应
      ElMessage.error(`${action}失败: ${error.response.data?.msg || `HTTP错误: ${error.response.status}`}`);
    } else {
      ElMessage.error(`${action}失败: ${error.message || '网络异常'}`);
    }
    console.error(`${action}供应商错误:`, error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchSupplierList();
});
</script>

<style scoped>
.supplier-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.list-card {
  background-color: #fff;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
